package com.zhouhong.LeetCode;

/**
 * @ClassName: Algorithm-and-Data-Structure
 * @Description:
 * @Author: zhouhong
 * @Create: 2021-04-01 13:44
 **/

public class LeetCode0203 {

    public ListNode removeElements1(ListNode head, int val) {
        while (head != null && head.val == val){
            head = head.next;
        }
        if (head == null){
            return null;
        }
        ListNode pre = head;
        while (pre.next != null){
            if (pre.next.val == val){
                pre.next = pre.next.next;
            }else {
                pre = pre.next;
            }
        }
        return head;
    }

    // 使用虚拟头结点实现
    public ListNode removeElements2(ListNode head, int val) {
        ListNode dummyHead = new ListNode(-1);
        dummyHead.next = head;
        ListNode pre = dummyHead;
        while (pre.next != null){
            if (pre.next.val == val){
                pre.next = pre.next.next;
            }else {
                pre = pre.next;
            }
        }
        return dummyHead.next;
    }
    // 使用递归实现
    public ListNode removeElements(ListNode head, int val) {
        if (head == null){
            return null;
        }
//        ListNode res = removeElements(head.next, val);
//        if (head.val == val){
//            return res;
//        }else {
//            head.next = res;
//            return head;
//        }

        head.next = removeElements(head.next, val);
        return head.val == val ? head.next : head;
    }
    public static void main(String[] args) {
        int[] nums = {1,2,6,3,4,5,6};
        ListNode head = new ListNode(nums);
        System.out.println(head);
        ListNode res = (new LeetCode0203()).removeElements(head, 6);
        System.out.println(res);
    }
}
















